package com.wontube.smr.web.pub;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.FileCopyUtils;

/**
 * @author tanggf(2012-5-16)
 *
 */
public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	
	public StringHttpMessageConverter() {
		super(new MediaType("text", "plain", DEFAULT_CHARSET), MediaType.ALL);		
	}
	
	@Override
	protected boolean supports(Class<?> clazz) {
		return String.class.equals(clazz);
	}

	@Override
	protected String readInternal(Class<? extends String> clazz,
			HttpInputMessage inputMessage) throws IOException,
			HttpMessageNotReadableException {		
		return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), DEFAULT_CHARSET));
	}

	@Override
	protected void writeInternal(String s, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), DEFAULT_CHARSET));		
	}
}
